﻿/*
 * Copyright © 2025−2026 WEI.ZHOU (Willis) (Chengdu). All rights reserved.
 *
 * THIS SOURCE CODE IS PROPRIETARY AND CONFIDENTIAL.
 * It is the exclusive property of WEI.ZHOU (Willis) and may not be
 * used, copied, distributed, or disclosed outside of WEI.ZHOU (Willis)
 * without express written permission.
 *
 * This code is provided to WEI.ZHOU (Willis) under a limited, 
 * non-transferable internal license, and is for use only with the author's 
 * approved purposes. No external license is granted or implied.
 *
 * Any unauthorized use, reproduction, or distribution is strictly prohibited
 * and may result in severe civil and criminal penalties.
 */

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System.Text.Json;

namespace Aore.Core.BaseModels;

public class ApiResult : IActionResult
{
  /// <summary>
  /// 是否成功
  /// </summary>
  public bool Success { get; set; }
  
  /// <summary>
  /// 错误信息
  /// </summary>
  public string? Message { get; set; }

  /// <summary>
  /// 错误码
  /// </summary>
  public string? Code { get; set; }
  
  /// <summary>
  ///  数据
  /// </summary>
  public object? Context { get; set; }

  /// <summary>
  /// 执行时间
  /// </summary>
  public string? ExecultTime { get; set; }

  /// <summary>
  /// 转为字符串
  /// </summary>
  /// <returns></returns>
  public override string ToString()
  {
    return
      $"{{\"success\": {Success}, \"message\": \"{Message}\", \"code\": \"{Code}\", \"context\": {Context}, \"execultTime\": \"{ExecultTime}\"}}";
  }

  public async Task ExecuteResultAsync(ActionContext context)
  {
    // 获取响应对象
    var response = context.HttpContext.Response;
        
    // 设置内容类型
    response.ContentType = "application/json; charset=utf-8";
        
    // 设置HTTP状态码（将业务状态码映射为HTTP状态码）
    response.StatusCode = MapToHttpStatusCode(Convert.ToInt32(Code));
        
    // 创建JSON序列化选项
    var jsonOptions = context.HttpContext.RequestServices
      .GetRequiredService<IOptions<JsonOptions>>().Value;
        
    // 序列化ApiResult对象
    var json = JsonSerializer.Serialize(this, jsonOptions.JsonSerializerOptions);
        
    // 写入响应体
    await response.WriteAsync(json);
  }

  private int MapToHttpStatusCode(int businessCode)
  {
    // 将业务状态码映射为HTTP状态码
    return businessCode switch
    {
      0 => StatusCodes.Status200OK,
      1 => StatusCodes.Status200OK,
      200 => StatusCodes.Status200OK,
      400 => StatusCodes.Status400BadRequest,
      401 => StatusCodes.Status401Unauthorized,
      403 => StatusCodes.Status403Forbidden,
      404 => StatusCodes.Status404NotFound,
      500 => StatusCodes.Status500InternalServerError,
      _ => StatusCodes.Status500InternalServerError
    };
  }
}
